package edu.tjpu.share.newui;

import java.io.FileNotFoundException;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.FileForUpload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.task.SaveFileListTask;
import edu.tjpu.share.util.BitMapDrawableUtil;
import edu.tjpu.share.util.FileUtil;

public class NewMessage extends Activity {

	private EditText new_message;
	private String new_msg;
	private Button send_msg;
	private ImageButton add_picture;
	private ImageButton add_audio;
	private ImageButton add_file;
	private UserVo user;
	private Server serverinfo;
	private ImageView scan_picture;
	private Bitmap backBitmap;
	private Bitmap newBitmap;
	private java.io.File newFile;
	private java.io.File newAudio;
	private boolean firstedit = true;
	Uri imageuri;
	String audio;
	String img_path;
	Uri fileuri;
	private static boolean status;
	ProgressDialog saveFileList;

	public static void setStatus(boolean status) {
		NewMessage.status = status;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_message);
		new_message = (EditText) findViewById(R.id.edit_new_message);
		add_picture = (ImageButton) findViewById(R.id.add_picture);
		add_audio = (ImageButton) findViewById(R.id.add_audio);
		add_file = (ImageButton) findViewById(R.id.add_file);
		send_msg = (Button) findViewById(R.id.send_msg);

		newBitmap = null;
		newFile = null;
		newAudio = null;
		status = false;
		
		java.io.File cache = NewMessage.this.getCacheDir();
		java.io.File cacheServerinfoFile = new java.io.File(cache,
				Fields.SERVER_INFO);
		java.io.File cacheUserFile = new java.io.File(cache,
				Fields.USER);
		user = (UserVo) FileUtil.ReadObjectFromFile(cacheUserFile
				.getAbsolutePath());
		serverinfo = (Server) FileUtil.ReadObjectFromFile(cacheServerinfoFile
				.getAbsolutePath());

		send_msg.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {

				new_msg = new_message.getText().toString().trim();
				if (TextUtils.isEmpty(new_msg)) {
					Toast.makeText(NewMessage.this, "输入框不能为空",
							Toast.LENGTH_SHORT).show();
				} else {

					FileForUpload upfile = new FileForUpload();
					saveFileList = ProgressDialog.show(NewMessage.this,
							"请稍等...", "正在写入缓存...", true);
					java.io.File cache = NewMessage.this.getCacheDir();
					java.io.File cacheFile = new java.io.File(cache,
							Fields.TEMP_FILE);
					if (newBitmap != null) {

						upfile.setUid(user.getUid());
						upfile.setMsg(new_msg);

						upfile.setFname(img_path.substring(
								img_path.lastIndexOf("/") + 1,
								img_path.length()));

						FileUtil.wirteByteToFile(
								BitMapDrawableUtil.getBitmapByte(newBitmap),
								cacheFile.getAbsolutePath());
						upfile.setFurl(cacheFile.getAbsolutePath());
					}

					else if (newAudio != null) {
						String audioPath = newAudio.getAbsolutePath();
						upfile.setUid(user.getUid());
						upfile.setMsg(new_msg);
						upfile.setFname(audioPath.substring(
								audioPath.lastIndexOf("/") + 1,
								audioPath.length()));
						upfile.setFurl(audioPath);
					}

					else if (newFile != null) {
						upfile.setUid(user.getUid());
						upfile.setMsg(new_msg);
						String str = fileuri.getPath();
						upfile.setFname(str.substring(str.lastIndexOf("/") + 1,
								str.length()));
						upfile.setFurl(newFile.getAbsolutePath());
					} else {
						upfile.setUid(user.getUid());
						upfile.setMsg(new_msg);
					}

					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put(Fields.FILE_URL, cache);
					map.put(Fields.FILE_FORUPLOAD, upfile);
					map.put(Fields.HANDLER, handlerSaveFileList);
					new SaveFileListTask().execute(map);

				}

			}
		});

		add_picture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				scan_picture = (ImageView) findViewById(R.id.add_picture_view);
				scan_picture.setLongClickable(true);
				Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
				// 查看类型 String, IMAGE_UNSPECIFIED, "image/*";
				innerIntent.setType(Fields.IMAGE_UNSPECIFIED);
				Intent wrapperIntent = Intent
						.createChooser(innerIntent, "选择图片");
				((Activity) NewMessage.this).startActivityForResult(
						wrapperIntent, Fields.ACTIVITY_GET_IMAGE);
				wrapperIntent.putExtra("return-data", true);
			}
		});

		add_audio.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
				innerIntent.setType(Fields.AUDIO_UNSPECIFIED);
				Intent wrapperIntent = Intent
						.createChooser(innerIntent, "选择音频");
				((Activity) NewMessage.this).startActivityForResult(
						wrapperIntent, Fields.ACTIVITY_GET_AUDIO);
				wrapperIntent.putExtra("return-data", true);
			}
		});

		add_file.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);

				innerIntent.setType(Fields.FILE_UNSPECIFIED);

				Intent wrapperIntent = Intent
						.createChooser(innerIntent, "选择文件");

				((Activity) NewMessage.this).startActivityForResult(
						wrapperIntent, Fields.ACTIVITY_GET_FILE);
				wrapperIntent.putExtra("return-data", true);
			}
		});
	}

	private Handler handlerSaveFileList = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (status) {
				Intent intent = NewMessage.this.getIntent();
				Bundle bundle = new Bundle();;

				bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
				bundle.putSerializable(Fields.USER, user);
				bundle.putSerializable(Fields.IS_REG, false);
				intent.putExtras(bundle);
				intent.setClass(NewMessage.this, GetAcademy.class);

				saveFileList.dismiss();

				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
				startActivity(intent);
				//finish();

			} else {
				saveFileList.dismiss();
				Toast.makeText(NewMessage.this, "缓存写入失败！", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	// ///////////////////-------vincent---//////////////////////////
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			if (data != null) {
				if (requestCode == Fields.ACTIVITY_GET_IMAGE) {
					scan_picture.setVisibility(View.VISIBLE);
					imageuri = data.getData();
					if (imageuri.isRelative()
							|| imageuri.toString().contains("content://")) {

						String[] proj = { MediaStore.Images.Media.DATA };

						Cursor actualimagecursor = managedQuery(imageuri, proj,
								null, null, null);

						int actual_image_column_index = actualimagecursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

						actualimagecursor.moveToFirst();

						img_path = actualimagecursor
								.getString(actual_image_column_index);
					} else {
						img_path = imageuri.getPath();
					}
					ContentResolver cr = this.getContentResolver();
					try {
						backBitmap = BitmapFactory.decodeStream(cr
								.openInputStream(imageuri));
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					newBitmap = Bitmap.createBitmap(backBitmap);
					/* 将Bitmap设定到ImageView */
					scan_picture.setScaleType(ImageView.ScaleType.CENTER);
					scan_picture.setImageBitmap(newBitmap);
					scan_picture
							.setOnCreateContextMenuListener(new ScanContextListener());
				}
				if (requestCode == Fields.BG_BITMAP) {
					Bundle path = data.getExtras();
					String tmp = path.getString(Fields.BITMAP_PATH);
					newBitmap = BitmapFactory.decodeFile(tmp);
					firstedit = false;
					/* 将Bitmap设定到ImageView */
					scan_picture.setScaleType(ImageView.ScaleType.CENTER);
					scan_picture.setImageBitmap(newBitmap);
					scan_picture
							.setOnCreateContextMenuListener(new ScanContextListener());
				}
				if (requestCode == Fields.ACTIVITY_GET_FILE) {
					fileuri = data.getData();
					newFile = new java.io.File(fileuri.getPath());
				}
				if (requestCode == Fields.ACTIVITY_GET_AUDIO) {
					Uri audiouri = data.getData();
					if (audiouri.isRelative()
							|| audiouri.toString().contains("content://")) {
						String[] proj = { MediaStore.Audio.Media.DATA };

						Cursor actualaudiocursor = managedQuery(audiouri, proj,
								null, null, null);

						int actual_audio_column_index = actualaudiocursor
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);

						actualaudiocursor.moveToFirst();

						audio = actualaudiocursor
								.getString(actual_audio_column_index);

						newAudio = new java.io.File(audio);
					} else {
						newAudio = new java.io.File(audiouri.getPath());
					}
				}

			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private class ScanContextListener implements OnCreateContextMenuListener {

		@Override
		public void onCreateContextMenu(ContextMenu contextMenu, View view,
				ContextMenuInfo arg2) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.picture_menu, contextMenu);
			contextMenu.setHeaderTitle("图片操作");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.picture_draw:
			// 修改图片
			if (firstedit) {
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putParcelable(Fields.BITMAP_TO_DO, newBitmap);
				intent.putExtras(bundle);
				intent.setClass(NewMessage.this, PicturePad.class);
				startActivityForResult(intent, Fields.BG_BITMAP);
			} else {
				Toast.makeText(NewMessage.this, "您已经编辑过此图片！",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.picture_redo:
			// 重选图片
			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
			// 查看类型 String, IMAGE_UNSPECIFIED, "image/*";
			innerIntent.setType(Fields.IMAGE_UNSPECIFIED);
			Intent wrapperIntent = Intent.createChooser(innerIntent, "选择图片");
			((Activity) NewMessage.this).startActivityForResult(wrapperIntent,
					Fields.ACTIVITY_GET_IMAGE);
			firstedit = true;
			break;
		case R.id.picture_delete:
			// TODO 删除图片
			scan_picture.setImageBitmap(null);
			scan_picture.setVisibility(View.GONE);
			firstedit = true;
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	// ////////////////---vincent------///////////////////////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.general_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			// 关于Share

			break;
		case R.id.logout:
			// 退出Share
			//finish();
			Intent startMain = new Intent(Intent.ACTION_MAIN); 
            startMain.addCategory(Intent.CATEGORY_HOME); 
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            startActivity(startMain); 
            System.exit(0);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		// 按下键盘上返回按钮
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("您确定要退出吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									//finish();
									Intent startMain = new Intent(Intent.ACTION_MAIN); 
					                 startMain.addCategory(Intent.CATEGORY_HOME); 
					                 startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
					                 startActivity(startMain); 
					                 System.exit(0);
								}
							}).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
